# -*- coding: utf-8 -*-
import os
# import numpy as np
import pandas as pd
import wrf_output


def OutputToASCII(outputFile, ncols, nrows, cellSize, data, noDataValue=0):
    # np.savetxt(outputFile, data, delimiter='\t', fmt='%.2f')
    data.to_csv(r'test.txt',
                sep='\t', index=False, header=False, float_format='%.2f')
    with open(outputFile, 'w') as output_file:
        output_file.seek(0)
        output_file.write("NCOLS " + str(ncols) + "\n")
        output_file.write("NROWS " + str(nrows) + "\n")
        output_file.write("XLLCORNER 354644\n")
        output_file.write("YLLCORNER 365200\n")
        output_file.write("CELLSIZE " + str(cellSize) + "\n")
        output_file.write("NODATA_VALUE " + str(noDataValue) + "\n")
        input_file = open(r'test.txt', 'r')
        output_file.writelines(input_file.readlines())
        input_file.close()
        output_file.close()
    os.remove(r'test.txt')


def main(path, domain, startTime, outputPath):
    mp = ['2', '6', '7']
    cu = ['0', '1', '2', '10']
    gridSpacing = path.split('/')[-2]
    cellSize = 0
    if gridSpacing == '139':
        cellSize = 1000
    elif gridSpacing == '51545':
        cellSize = 5000
    elif gridSpacing == '103090':
        cellSize = 10000
    for i in mp:
        for j in cu:
            mp_cu = i + j
            if os.path.exists(path + mp_cu + '/'):
                input = path + mp_cu + '/wrfout_d' + domain + '_' + startTime
                accum = wrf_output.GetAccum(input)
                # accum = np.asarray(accum)
                accum = pd.DataFrame(accum)
                nrows, ncols = accum.shape
                if not os.path.exists(outputPath):
                    os.makedirs(outputPath)
                OutputToASCII(outputPath + mp_cu + '.txt', ncols, nrows, cellSize, accum)


if __name__ == '__main__':
    inputPath = r'F:/Research/WRF_Output/2008/12/1200/103090/'
    outputPath = r'F:/Research/ProcessResult/2008/12/1200/103090/'
    domain = r'03'
    startTime = r'2008-12-12_00_00_00'
    main(inputPath, domain, startTime, outputPath)
